﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using MasterTemplate = Cms.Domain.MasterTemplate;

namespace Cms.Web.UI.Admin
{
    public partial class EditDetailTemplate : AdminPage, IEditDetailTemplateView
    {
        private EditDetailTemplatePresenter _presenter;

        #region IEditDetailTemplateView Members

        public int DetailTemplateID
        {
            get
            {
                if (ViewState["DetailTemplateID"] == null)
                {
                    ViewState["DetailTemplateID"] = QueryString.GetInt32ID("id");
                }
                return (int)ViewState["DetailTemplateID"];
            }
        }
        
        public void SetDetailTemplateID(int id)
        {
            ViewState["DetailTemplateID"] = id;
        }
        
        public string Name
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }
        
        public string Description
        {
            get { return txtDescription.Text; }
            set { txtDescription.Text = value; }
        }
        
        public string SourceCode
        {
            get { return hidCode.Value; }
            set { hidCode.Value = value; }
        }
        
        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditDetailTemplate.xml"; }
        }

        public string CurrentTab
        {
            get { return tabStrip.CurrentValue; }
        }
        
        public string GetSourceCodeStatus()
        {
            string url = Url.FullPath + "Admin/SitePreview.aspx?LocaleID=" + SelectedLocaleID +
                         "&MasterTemplateID=" + SelectedMasterTemplateID +
                         "&TestDetailTemplate=true";
            var req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp;
            string result = string.Empty;
            string path = UserPhysicalTempDirectory + "TestDetailTemplate.master";
            IDiskAccess diskAccess = new DiskAccess();
            diskAccess.DeleteFile(path);
            diskAccess.CreateTextFile(path, SourceCode);
            req.Method = "GET";
            var cc = new CookieContainer();
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            var c = new Cookie(authCookie.Name, authCookie.Value, authCookie.Path, Request.Url.Host);
            cc.Add(c);
            req.CookieContainer = cc;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    result = "ok";
                }
                PageAreas = resp.Headers["DetailTemplatePageAreas"];
                DetailTemplateAreas = resp.Headers["DetailTemplateAreas"];
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    resp = ex.Response as HttpWebResponse;
                    if (resp != null)
                    {
                        var sr = new StreamReader(resp.GetResponseStream());
                        result = sr.ReadToEnd();
                        sr.Close();
                        sr.Dispose();
                        path = UserPhysicalTempDirectory + "ErrorDetails.aspx";
                        diskAccess.DeleteFile(path);
                        diskAccess.CreateTextFile(path, result);
                        result = result.Substring(result.IndexOf("<title>", StringComparison.InvariantCultureIgnoreCase) + 7);
                        result = result.Substring(0, result.IndexOf("</title>", StringComparison.InvariantCultureIgnoreCase));
                    }
                }
            }
            return result;
        }

        public void SetLocales(IList<Locale> locales)
        {
            ddlLocales.Items.Clear();
            foreach (Locale l in locales)
            {
                ddlLocales.Items.Add(new ListItem(l.GetTranslation(Localization).Name, l.ID.ToString()));
            }
        }

        public int SelectedLocaleID
        {
            get { return int.Parse(ddlLocales.SelectedValue); }
            set { ddlLocales.SelectedValue = value.ToString(); }
        }
        
        public void SetVersions(IList<ContentTranslationVersion> versions, int publishedVersionID)
        {
            ContentSetContainerHelper.SetVersions(
                versions,
                publishedVersionID,
                GetText(this, "NoContentVersions"),
                ref ddlVersions,
                ref lbPublish,
                ref hlPublishLater,
                ref lbSelectPublishedVersion,
                ref llNoVersionPublished);
        }
        
        public int SelectedVersionID
        {
            get { return int.Parse(ddlVersions.SelectedValue); }
            set { ddlVersions.SelectedValue = value.ToString(); }
        }
        
        public void SetScheduledPublishings(IList<ScheduledPublishing> scheduledPublishings)
        {
            rpScheduledPublishings.DataSource = scheduledPublishings;
            rpScheduledPublishings.DataBind();
            pnlScheduledPublishings.Visible = scheduledPublishings.Count > 0;
        }
        
        public string DetailTemplateAreas
        {
            get { return (string)ViewState["DetailTemplateAreas"]; }
            set { ViewState["DetailTemplateAreas"] = value; }
        }
        
        public string PageAreas
        {
            get { return (string)ViewState["PageAreas"]; }
            set { ViewState["PageAreas"] = value; }
        }

        public void SetMasterTemplates(IList<MasterTemplate> masterTemplates)
        {
            ddlMasterTemplates.Items.Clear();
            ddlPreferredMasterTemplates.Items.Clear();
            foreach (MasterTemplate mt in masterTemplates)
            {
                ddlMasterTemplates.Items.Add(new ListItem(mt.Name, mt.ID.ToString()));
                ddlPreferredMasterTemplates.Items.Add(new ListItem(mt.Name, mt.ID.ToString()));
            }
        }

        public int SelectedMasterTemplateID
        {
            get { return int.Parse(ddlMasterTemplates.SelectedValue); }
            set { ddlMasterTemplates.SelectedValue = value.ToString(); }
        }
        
        public int SelectedPreferredMasterTemplateID
        {
            get { return int.Parse(ddlPreferredMasterTemplates.SelectedValue); }
            set { ddlPreferredMasterTemplates.SelectedValue = value.ToString(); }
        }
        
        public void PublishContentNotAllowed()
        {
            lbPublish.Visible = false;
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new EditDetailTemplatePresenter(this);
            int selectedIndex = ddlLocales.SelectedIndex;
            _presenter.SetLocales();
            ddlLocales.SelectedIndex = selectedIndex;
            if (!Page.IsPostBack)
            {
                if (DetailTemplateID > 0)
                {
                    tabStrip.SelectedValue = Request.QueryString["tab"];
                }
                else
                {
                    // The code below doesn't work because of editArea. Try a javascript approach instead.
                    //txtName.Focus();
                }
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
            }
            tiProperties.OnClientClick =
                "cms.Edit.ShowTabOverlays(); updateCode(); if (isDirty()) return cms.Dialogs.ConfirmLinkButton(this, " +
                "function (status) { if (status != 'ok') cms.Edit.HideTabOverlays(); }, " +
                "'" + GetText(this, "SaveInfoHeader") + "', " +
                "'" + GetText(this, "SaveInfoMessage") + "', " +
                "'" + GetText(this, "SaveInfoOK") + "', " +
                "'" + GetText(this, "SaveInfoCancel") + "', " +
                "true, " +
                "null);";
            tiContent.OnClientClick = tiProperties.OnClientClick;
            hlPublishLater.Attributes.Add(
                "onclick",
                "initInlineDateTimePicker(); cms.Dialogs.Confirm(schedulePublishingCallback, '" +
                GetText(this, "PublishLaterHeader") +
                "', null, '" +
                GetText(this, "SaveInfoOK") +
                "', '" +
                GetText(this, "SaveInfoCancel") +
                "', true, null, 'schedulePublishing');");
            ClientScriptProxy.Current.RegisterClientScriptBlock(
                tabStrip, 
                GetType(),
                "confirmMasterTemplateContentEditing",
                "function confirmMasterTemplateContentEditing(redirectCallback) {" +
                "return cms.Dialogs.Confirm(redirectCallback, " +
                "'" +
                GetText(this, "EditMasterTemplateContentWarningHeader") +
                "', " +
                "'" +
                GetText(this, "EditMasterTemplateContentWarningMessage") +
                "', " +
                "'" +
                GetText(this, "EditMasterTemplateContentWarningOK") +
                "', " +
                "'" +
                GetText(this, "EditMasterTemplateContentWarningCancel") +
                "', " +
                "null, " +
                "null);" +
                "}",
                true);
            if (DetailTemplateID > 0)
            {
                HeadingText = GetText(this, "EditDetailTemplateHeading") + " &mdash; " + Name;
            }
            else
            {
                HeadingText = GetText(this, "NewDetailTemplateHeading");
            }
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Page.Header.Controls.Add(new LiteralControl(
                "<script type=\"text/javascript\">" +
                DatePickerHelper.GetDatePickerSetup(Localization) +
                Environment.NewLine +
                DatePickerHelper.GetInlineDatePickerSetup(Localization, true) +
                "</script>"));
        }

        protected void btnTriggerBreakContentLinkConfirmation_Click(object sender, EventArgs e)
        {
            string list = "<ul>";
            foreach (ContentSetContainer container in _presenter.GetContentContainers(hidBreakLinkAreaID.Value, hidBreakLinkContentType.Value))
            {
                list += "<li>" + Server.HtmlEncode(container.Name) + "</li>";
            }
            list += "</ul>";
            string script = "cms.Dialogs.Confirm(breakContentLinkCallback, " +
                            "'" + GetText(this, "BreakContentLinkHeader") + "', " +
                            "'" + GetText(this, "BreakContentLinkMessage").Replace("[List]", list).Replace("'", @"\'") +
                            "', " +
                            "'" + GetText(this, "BreakContentLinkOK") + "', " +
                            "'" + GetText(this, "BreakContentLinkCancel") + "', " +
                            "true, " +
                            "null);";
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "confirmBreakContentLink", script, true);
        }
        
        protected void btnBreakContentLink_Click(object sender, EventArgs e)
        {
            _presenter.BreakContentLink(hidBreakLinkAreaID.Value, hidBreakLinkContentType.Value);
            upnlContent.Update();
        }
        
        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            if (tabStrip.SelectedValue == "content" && Request.Form[btnTriggerBreakContentLinkConfirmation.UniqueID] == null)
            {
                ifrPreview.Attributes.Add(
                    "src", 
                    "Admin/SitePreview.aspx?PreviewMode=detailtemplate" +
                    "&LocaleID=" + SelectedLocaleID +
                    "&VersionID=" + SelectedVersionID +
                    "&MasterTemplateID=" + SelectedMasterTemplateID +
                    "&DetailTemplateID=" + DetailTemplateID +
                    "&AllowContentEditing=true");
                upnlContent.Update();
            }
            ClientScriptProxy.Current.RegisterStartupScript(
                tabStrip, 
                GetType(),
                "updatePanels",
                "updatePanels('" + tabStrip.SelectedValue + "');", 
                true);
        }
        
        protected void lbSave_Click(object sender, EventArgs e)
        {
            Save();
        }
        
        protected void lbPublish_Click(object sender, EventArgs e)
        {
            _presenter.Publish();
        }

        protected void lbSelectPublishedVersion_Click(object sender, EventArgs e)
        {
            ddlVersions.SelectedValue = (sender as LinkButton).CommandArgument;
            upnlContent.Update();
        }
        
        protected void btnSchedulePublishing_Click(object sender, EventArgs e)
        {
            _presenter.SchedulePublishing(int.Parse(ddlVersions.SelectedValue), DateTime.Parse(hidScheduledPublishing.Value));
            upnlContent.Update();
        }
        
        protected void lbSaveAndReturn_Click(object sender, EventArgs e)
        {
            Save();
            if (_presenter.IsValid)
            {
                Response.Redirect("DetailTemplates.aspx");
            }
        }
        
        protected void tabStrip_Click(string value)
        {
            Save();
            if (_presenter.IsValid)
            {
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            }
        }
        
        protected void ddlLocales_IndexChanged(object sender, EventArgs e)
        {
            _presenter.SaveSelectedLocale();
            _presenter.SetVersions();
            upnlContent.Update();
        }
        
        protected void ddlVersions_IndexChanged(object sender, EventArgs e)
        {
            upnlContent.Update();
        }
        
        protected void ddlMasterTemplates_IndexChanged(object sender, EventArgs e)
        {
            upnlContent.Update();
        }
        
        protected void rpScheduledPublishings_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }
            var scheduledPublishing = (ScheduledPublishing)e.Item.DataItem;
            var litVersion = (Literal)e.Item.FindControl("litVersion");
            var litTimestamp = (Literal)e.Item.FindControl("litTimestamp");
            var lbDeleteScheduledPublishing = (LinkButton)e.Item.FindControl("lbDeleteScheduledPublishing");
            litVersion.Text = "#" + scheduledPublishing.ContentTranslationVersion.ID;
            var timestamp = new DateTime(long.Parse(scheduledPublishing.Timestamp));
            litTimestamp.Text = timestamp.ToShortDateString() + " " + timestamp.ToShortTimeString();
            lbDeleteScheduledPublishing.CommandArgument = scheduledPublishing.ID.ToString();
        }
        
        protected void lbDeleteScheduledPublishing_Click(object sender, EventArgs e)
        {
            _presenter.DeleteScheduledPublishing(int.Parse((sender as LinkButton).CommandArgument));
            upnlContent.Update();
        }

        private void Save()
        {
            if (hidIsDirty.Value == "true")
            {
                _presenter.Save();
            }
        }
    }
}